package com.sam.im.sms.index.activitys;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.PhoneLookup;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sam.im.sms.R;
import com.sam.im.sms.beans.MessageWrap;
import com.sam.im.sms.util.NotificationUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * AsyncQueryHandler 异步数据库查询 CursorAdapter 就是数据库的特有的适配器 获取短信的url
 *
 * @author wyf
 */
public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    ListView mListView;
    TextView add;
    TextView setting;
    TextView tv_refuse;
    private CursorAdapter mAdapter;
    private MyAsyncQueryHandler asyncQueryHandler;
    private String[] projection = new String[]{"sms.thread_id AS _id",
            "sms.body AS snippet", "groups.msg_count AS msg_count",
            "sms.address AS address", "sms.date AS date"};

    private String[] contentProjection = new String[]{PhoneLookup._ID,
            PhoneLookup.DISPLAY_NAME};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.mListView);
        add = findViewById(R.id.add);
        tv_refuse = findViewById(R.id.tv_refuse);
        setting = findViewById(R.id.setting);
        setting.setOnClickListener(this::onClick);
        add.setOnClickListener(this::onClick);
        tv_refuse.setOnClickListener(this::onClick);
        mAdapter = new MyAdatper(this, null);

        // 获取数据库数据
        mListView.setAdapter(mAdapter);
        asyncQueryHandler = new MyAsyncQueryHandler(getContentResolver());
        asyncQueryHandler.startQuery(0, null,
                Uri.parse("content://sms/conversations/"), projection, null,
                null, " date desc");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add:
                startActivity(new Intent(this, NewSmsActivity.class));
                break;
            case R.id.setting:
                startActivity(new Intent(this, SmsSettingActivity.class));
                break;
            case R.id.tv_refuse:
                startActivity(new Intent(this, RefuseMailboxActivity.class));
                break;
        }
    }

    class MyAsyncQueryHandler extends AsyncQueryHandler {

        public MyAsyncQueryHandler(ContentResolver cr) {
            super(cr);
            // TODO Auto-generated constructor stub
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            super.onQueryComplete(token, cookie, cursor);
            Log.i(TAG, "onQueryComplete" + (cursor == null));
            mAdapter.changeCursor(cursor);
        }
    }


    class MyAdatper extends CursorAdapter {

        private ViewHolder mHolder;

        public MyAdatper(Context context, Cursor c) {
            super(context, c);
            // TODO Auto-generated constructor stub
        }

        /**
         * "sms.thread_id AS _id", "sms.body AS snippet",
         * "groups.msg_count AS msg_count", "sms.address AS address",
         * "sms.date AS date"
         * <p>
         * private String[] projection = new String[] { "_id", "address", "person",
         * "body", "type", "date" };
         */
        @Override
        public void bindView(View view, Context arg1, Cursor cursor) {
            if (view != null) {
                mHolder = (ViewHolder) view.getTag();
                TextView nameTv = mHolder.name;
                TextView contentTv = mHolder.txt_date_title;
                RelativeLayout rlTitle = mHolder.rlTitle;
                TextView txtDateTimeTv = mHolder.txtDateTime;
                final String thread_id = cursor.getString(0);
                String content = cursor.getString(1);
                int count = cursor.getInt(2);
                final String address = cursor.getString(3);
                long date = cursor.getLong(4);
//                Log.e("lyc","thread_id>>>"+thread_id+"content>>>"+content+"count>>>"+count+"address>>>>"+address+"date>>>>"+date);
                // 短信内容
                if (content != null && content.length() > 20) {
                    contentTv.setText(content.substring(0, 20));
                } else {
                    contentTv.setText(content);

                }

                // 次数--时间--java基础知识，获取时间的
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(date);

                SimpleDateFormat format = new SimpleDateFormat(
                        "MM/dd");
                String formatTime = format.format(calendar.getTime());
                txtDateTimeTv.setText(formatTime);

                /**
                 * 定义成局部变量，不要定义成成员变量
                 */
                String phoneName = null;
                Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                        Uri.encode(address));
                Cursor concatCursor = getContentResolver().query(uri,
                        contentProjection, null, null, null);
                if (concatCursor.moveToFirst()) {
                    // 查询到了联系人
                    phoneName = concatCursor.getString(1);
                }
                concatCursor.close();

                if (phoneName != null) {
                    nameTv.setText(phoneName);
                    Log.i(TAG, "phoneName:" + phoneName);
                } else {
                    nameTv.setText(address);
                    Log.i(TAG, "address:" + address);
                }

                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this, ThreadDetailActivity.class);
                        intent.putExtra("phone", address);
                        startActivity(intent);
                    }
                });
                view.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage("确定删除该信息么");
                        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContentResolver CR = getContentResolver();
                                CR.delete(Uri.parse("content://sms/conversations/" + thread_id), null, null);
                            }
                        });
                        builder.show();
                        return true;
                    }
                });
            }

        }

        @Override
        public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
            View view = null;
            if (view == null) {
                mHolder = new ViewHolder();
                view = View.inflate(getApplicationContext(), R.layout.item,
                        null);
            }

            mHolder.name = (TextView) view.findViewById(R.id.name);
            mHolder.txt_date_title = (TextView) view.findViewById(R.id.txt_date_title);
            mHolder.rlTitle = view.findViewById(R.id.rl_title);
            mHolder.txtDateTime = view.findViewById(R.id.txt_date_time);

            view.setTag(mHolder);
            return view;

        }


    }


    class ViewHolder {
        TextView name;
        TextView txt_date_title;
        TextView txtDateTime;
        RelativeLayout rlTitle;
    }
}